use std::env;
use std::error::Error;
use std::fs;
use std::vec;

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    // 读取文件
    let results: String = fs::read_to_string(config.filename).expect("文件不存在！");

    let r_result = if config.case_sensitive {
        search(&config.query, &results)
    }else {
        search_sensitive(&config.query, &results)
    };

    for r in r_result {
        println!("{}", r);
    }
    Ok(())
}

pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config {
    pub fn new(args: &Vec<String>) -> Config {
        let query = args[1].clone();
        let filename = args[2].clone();
        let case_sensitive = env::var("CASE_SENSITIVE").is_err();
        Config {
            query,
            filename,
            case_sensitive,
        }
    }
}

// 在txt中查询字符串
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut result = vec![];

    for lines in contents.lines() {
        if lines.contains(query) {
            result.push(lines)
        }
    }

    result
}


// 在txt中查询字符串-不区分大小写
pub fn search_sensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = &query.to_lowercase();
    let mut result = vec![];

    for lines in contents.lines() {
        if lines.contains(query) {
            result.push(lines)
        }
    }

    result 
}

// TDD 测试驱动开发
#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_search() {
        let contents = "正如习近平总书记所说下：

        
“他们信仰的理想正在实现，他们开创的事业正在继续，他们书写的历史必将由我们继续书写下去。”这是对革命先烈的深情告慰，也是对我们莫大的激励和鞭策。
盛世如斯，123.
盛世如斯，相信不仅如您所愿，更会超您所愿！";

        assert_eq!(
            vec!["盛世如斯，相信不仅如您所愿，更会超您所愿！"],
            search("盛世如斯", contents)
        )
    }

  
}
